﻿using System;
using FluentValidation;
using FluentValidation.Results;
using GiveAQuiz.Web.Helpers;
using GiveAQuiz.Web.Membership;
using GiveAQuiz.Web.Models;

namespace GiveAQuiz.Web.Validation
{
  /// <summary>
  /// Validates the RegistrationViewModel
  /// </summary>
  public class RegistrationValidator : AbstractValidator<RegistrationViewModel>
  {
    /// <summary>
    /// Creates a new instance of the RegistrationValidator
    /// </summary>
    /// <param name="membershipSvc">The IMembershipService interface that provides
    /// information about the Membership Provder. </param>
    public RegistrationValidator(IMembershipService membershipSvc)
    {
      // user name
      RuleFor(r => r.UserName).NotBlank().WithMessage("Username is required");

      // password
      RuleFor(r => r.Password).NotBlank().WithMessage("Password is required");
      RuleFor(r => r.Password.Length)
        .GreaterThanOrEqualTo(membershipSvc.MinPasswordLength)
        .When(r => !String.IsNullOrWhiteSpace(r.Password))
        .WithMessage(String.Format("The new password must have {0} or more characters", membershipSvc.MinPasswordLength));

      // repeat password
      RuleFor(r => r.RepeatPassword).NotBlank().WithMessage("The repeat password is required");
      RuleFor(r => r.RepeatPassword.Length)
        .GreaterThanOrEqualTo(membershipSvc.MinPasswordLength)
        .When(r => !String.IsNullOrWhiteSpace(r.RepeatPassword))
        .WithMessage(String.Format("The repeat password must have {0} or more characters", membershipSvc.MinPasswordLength));

      // password and repeat must match
      Custom(r =>
        !String.IsNullOrWhiteSpace(r.Password) && !String.IsNullOrWhiteSpace(r.RepeatPassword) &&
        !r.Password.Equals(r.RepeatPassword, StringComparison.OrdinalIgnoreCase) ?
          new ValidationFailure("RepeatPassword", "The password and the confirmation do not match") : null);

      // email
      RuleFor(r => r.Email).NotBlank().WithMessage("Email is required");
      RuleFor(r => r.Email)
        .EmailAddress()
        .When(r => !String.IsNullOrWhiteSpace(r.Email))
        .WithMessage("Email address is invalid");
    }
  }  
}